package com.frank.oj.interceptor;

import com.frank.oj.annotation.HCOJAccess;
import com.frank.oj.annotation.HCOJAccessEnum;
import com.frank.oj.utils.ServiceContextUtils;
import com.frank.oj.validator.AccessValidator;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author frank
 * @Date 2024/3/22
 */
@Component
public class AccessInterceptor implements HandlerInterceptor {

    @Resource
    private AccessValidator accessValidator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 静态资源
        if (handler instanceof HandlerMethod) { //
            HandlerMethod handlerMethod = HandlerMethod.class.cast(handler);

            HCOJAccess hcojAccess = ServiceContextUtils.getAnnotation(handlerMethod.getMethod(), handlerMethod.getBeanType(), HCOJAccess.class);
            if (hcojAccess == null || hcojAccess.value().length == 0) {
                return true;
            }
            for (HCOJAccessEnum accessEnum : hcojAccess.value()) {
                accessValidator.validateAccess(accessEnum);
            }
            return true;
        } else return handler instanceof ResourceHttpRequestHandler;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
